package cn.hh.basic.util;

import cn.hh.basic.jwt.JwtUtils;
import cn.hh.basic.jwt.LoginData;
import cn.hh.basic.jwt.Payload;
import cn.hh.basic.jwt.RsaUtils;
import cn.hh.user.domain.Logininfo;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

public class LoginContext {

    /**
     *  获取当前登录人的登录信息
     * @param request
     * @return
     */
    public static Logininfo getLoginUser(HttpServletRequest request) {
        // 1.从请求头获取token - jwtToken
        String token = request.getHeader("token");
        if (token != null) { // 有值
            // 2.解密:
            // 2.1.获取公钥(私钥加密,就用公钥解密)
            try {
                PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                // 2.2.解密 通过JwtUtils调用静态方法getInfoFromToken, 传入三个参数() 1.token  2.publicKey  3.LoginData.calss
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
                // 2.3.获取Payload -> loginData -> logininfo
                return payload.getLoginData().getLogininfo();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
